<?php

namespace app\admin\controller\supplier;

use app\admin\model\Category;
use app\admin\model\Rule;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use jianyan\excel\Excel;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="supplier")
 */
class Supplier extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Supplier();

    }

    /**
     * @NodeAnotation(title="导出")
     */
    public function export()
    {
        list($page, $limit, $where) = $this->buildTableParames();

        $header = [
            ['*供应商名称', 'name'],
            ['*供应商简码', 'bn'],
            ['*角色名称', 'auth_name'],
            ['*接单预留时间(天)', 'accept_cycle'],
            ['*发货质检预留时间(天)', 'logistics_cycle'],
            ['*地址', 'address'],
            ['*联系人', 'linkman'],
            ['导出规则', 'export_rule'],
            ['*ERP联系人', 'erp_operater'],
            ['*AI工厂标识', 'ai_type']
        ];

        !empty($where) ? ($where[0][0] == 'id' ? $where[0][0] = $this->model->getName() . '.id' : '') : [];

        $data = [];
        $list = $this->model
            ->withJoin(['auth'], 'LEFT')
            ->where($where)
            ->limit(1000)
            ->order($this->model->getName() . '.id', 'desc')
            ->page($page, $limit)
            ->select()
            ->toArray();

        collection($list)->map(function ($item, $key) use (&$data) {
            $data[$key]['name'] = $item['name'];
            $data[$key]['bn'] = $item['bn'];
            $data[$key]['auth_name'] = $item['auth']['username'];
            $data[$key]['accept_cycle'] = $item['accept_cycle'];
            $data[$key]['logistics_cycle'] = $item['logistics_cycle'];
            $data[$key]['address'] = $item['address'];
            $data[$key]['linkman'] = $item['linkman'];
            $data[$key]['export_rule'] = $item['export_rule'];
            $data[$key]['erp_operater'] = \GuzzleHttp\json_encode($item['erp_operater']);
            $data[$key]['ai_type'] = $item['ai_type'];
        });

        $title = '厂商导出';
        $fileName = $title . '-' . date('Ymd', time());

        return Excel::exportData($data, $header, $fileName, 'xlsx');
    }


    /**
     * @NodeAnotation(title="货号模板导出",auth=false)
     */
    public function export_template()
    {

        $header = [
            ['*供应商名称', 'name'],
            ['*供应商简码', 'bn'],
            ['*接单预留时间(天)', 'accept_cycle'],
            ['*发货质检预留时间(天)', 'logistics_cycle'],
            ['*地址', 'address'],
            ['*联系人', 'linkman'],
            ['导出规则', 'export_rule'],
            ['*ERP联系人', 'erp_operater'],
            ['*AI工厂标识', 'ai_type']
        ];
        $title = '供应商模板';
        $fileName = $title . '-' . date('Ymd', time());
        return Excel::exportData([], $header, $fileName, 'xlsx');
    }

    /**
     * @NodeAnotation(title="导入")
     */
    public function import()
    {
        $row = $this->request->get();
        if ($this->request->isAjax()) {

//            获取上传文件
            $file = $this->request->file('file');

//           读取上传文档 从第二行开始
            $data = Excel::import($file, 2);

            $all = $this->model->field('id,bn')->select()->toArray();
            $all_bn = collection($all)->pluck('bn')->toArray();
            $all_check_bn = collection($all)->pluck('id','bn')->toArray();
            $time = time();
            $collect = collection($data);

            $data_need = [];
            $collect->map(function ($item, $key) use (&$data_need, $time) {
                $data_need[$key]['name'] = $item[0];
                $data_need[$key]['bn'] = $item[1];
                $data_need[$key]['accept_cycle'] = $item[2];
                $data_need[$key]['logistics_cycle'] = $item[3];
                $data_need[$key]['address'] = $item[4];
                $data_need[$key]['linkman'] = $item[5];
                $data_need[$key]['export_rule'] = json_encode($item[6]);
                $data_need[$key]['erp_operater'] = $item[7];
                $data_need[$key]['ai_type'] = $item[8];
                $data_need[$key]['create_time'] = $time;
                $data_need[$key]['update_time'] = $time;

            });

            // 工厂码 相同就更新 不同就插入
            $update_arr = [];
            $insert_collection = collection($data_need)->map(function ($item, $key) use (&$update_arr, $all,$all_bn,$all_check_bn) {

                if (in_array($item['bn'], $all_bn)) {
                    $item['id'] = $all_check_bn[$item['bn']];
                    $update_arr[] = $item;
                    return false;
                }

                return $item;
            });
            //过滤空数组
            $insert_data = array_filter($insert_collection->toArray());

//            dd($insert_data,$update_arr);
            // 启动事务
            Db::startTrans();
            try {
                $this->model->saveAll($update_arr);
                // 可以分段插入设置$limit  insertAll($date,$limit)
                $this->model->insertAll($insert_data);
                Db::commit();
                $status = true;

            } catch (\Exception $e) {
//                dd($e);
                Db::rollback();
                $status = false;

            }

            $status?$this->error('导入成功'):$this->error('导入失败');
        }

        $this->assign('row', $row);
        return $this->fetch();
    }


}